<?php

/**
 * TcpAuthorationService
 * 客户端数据包签名验证中心
 */
namespace App\Service\TcpServer;

use App\Service\BaseService;
use App\Service\Code\Normal;

class TcpAuthorationService extends BaseService
{
    const RPC_KEY = 'MangBangPlatformRpcDC#123456';//密钥key
    const RPC_EXPIRE_TIME = 60;
    
    /**
     * 获取token加签
     * @param array $param
     */
    public function getAuthTokenByParameters( $param = [] )
    {
        ksort($param);
        $string = json_encode($param,JSON_UNESCAPED_UNICODE);
        $string = rawurlencode($string);
        return sha1($string.self::RPC_KEY);
    }
    
    /**
     * 比较签名授权验证
     * @param array $param
     * @param string $token
     */
    public function checkRpcClientParametersAuthToken( array $param ,string $token )
    {
        if( isset($param['token']) ) {
            unset($param['token']);
        }
        
        if( empty($param['method']) ) {
            return Normal::returnCode(Normal::FAIL,"系统主参数method不存在");
        }

        if( !isset($param['argments']) ) {
            return Normal::returnCode(Normal::FAIL,"系统主参数argments不存在");
        }
        
        if( empty($param['timestamp']) ) {
            return Normal::returnCode(Normal::FAIL,"系统主参数timestamp不存在");
        }
        
        if( empty($param['request_id']) ) {
            return Normal::returnCode(Normal::FAIL,"系统主参数request_id不存在");
        }
        
        //验证时间是否过期
        if( time() - $param['timestamp'] > self::RPC_EXPIRE_TIME ) {
            return Normal::returnCode(Normal::FAIL,"请求时间已过期！");
        }
        
        $server_token = $this->getAuthTokenByParameters($param);
        if( $server_token != $token ) {
            //return Normal::returnCode(Normal::FAIL,"签名不正确");
        }
        
        return Normal::returnCode(Normal::SUC,"校验通过");
    }
}